package datastructure.array;

import lombok.ToString;

/**
 * 实现一个支持动态扩容的数组
 *
 * @author hubb
 * @Date 2019/3/28 20:12
 */
@ToString
public class Array {
    /**
     * 数组存储容器
     */
    private int[] data;
    /**
     * 默认容量
     */
    private int capacity = 10;

    /**
     * 实际数组大小
     */
    private int size;

    public Array() {
        this.data = new int[capacity];
        this.capacity = capacity;
        this.size = 0;
    }

    /**
     * 新增数据
     *
     * @param e
     */
    public void add(int e) {
        //是否需要扩容
        if (this.size == this.capacity) {
            resize();
        }
        data[size++] = e;
    }

    /**
     * 扩容
     */
    private void resize() {
        //创建一个比原先大一倍的新数组
        this.capacity = this.capacity * 2;
        int[] newArray = new int[capacity];
        //复制原有数组的元素
        for(int i = 0; i < this.size; i++) {
            newArray[i] = data[i];
        }
        data = newArray;
    }


}
